package com.heima.tlias.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.heima.tlias.anno.Log;
import com.heima.tlias.controller.request.ClazzQueryRequest;
import com.heima.tlias.dao.ClazzMapper;
import com.heima.tlias.dao.StudentMapper;
import com.heima.tlias.pojo.Clazz;
import com.heima.tlias.service.ClazzService;
import com.heima.tlias.utils.PageBean;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @Author Administrator
 * @Date 2024/5/4
 **/
@Service
@RequiredArgsConstructor
public class ClazzServiceImpl implements ClazzService {

    private final ClazzMapper clazzMapper;

    private final StudentMapper studentMapper;

    @Override
    public PageBean<Clazz> queryByPage(ClazzQueryRequest request) {
        //开启分页
        PageHelper.startPage(request.getPage(), request.getPageSize());
        //执行查询
        Page<Clazz> page = clazzMapper.queryByPage(request);
        return new PageBean<>(page.getTotal(), page.getResult());
    }

    @Override
    @Log
    public void insert(Clazz clazz) {
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.insert(clazz);
    }

    @Override
    public Clazz queryById(Integer id) {
        return clazzMapper.queryById(id);
    }

    @Override
    @Log
    public void updateById(Clazz clazz) {
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.updateById(clazz);
    }

    @Override
    @Log
    public void deleteById(Integer id) {
        //查询该班级是否分配了学生
        Long count = studentMapper.queryByClazzId(id);
        //如果没有分配学生直接删除班级
        if (count == 0) {
            clazzMapper.deleteById(id);
            return;
        }
        //如果分配了学生,返回错误信息
        throw new RuntimeException("该班级已分配学员不能删除");
    }

    @Override
    public List<Clazz> queryAll() {
        return clazzMapper.queryAll();
    }
}
